package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatPrivateMessageDTO;
import com.zenithmind.chat.pojo.vo.ChatPrivateMessageVO;
import com.zenithmind.chat.service.ChatPrivateMessageService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 私聊消息控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/chat/private")
@RequiredArgsConstructor
@Tag(name = "私聊消息管理", description = "私聊消息相关接口")
public class ChatPrivateMessageController {

    private final ChatPrivateMessageService privateMessageService;

    @GetMapping("/session/{sessionId}/messages")
    @Operation(summary = "获取会话消息", description = "获取指定会话的消息列表")
    public Result<List<ChatPrivateMessageVO>> getSessionMessages(
            @Parameter(description = "会话ID") @PathVariable String sessionId,
            @Parameter(description = "最后消息ID") @RequestParam(required = false) String lastMessageId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<ChatPrivateMessageVO> messages = privateMessageService.getSessionMessages(sessionId, userId, lastMessageId, limit);
        return Result.success(messages);
    }

    @GetMapping("/session/{sessionId}/page")
    @Operation(summary = "分页查询消息", description = "分页查询会话消息")
    public Result<PageResult<ChatPrivateMessageVO>> getMessagePage(
            @Parameter(description = "会话ID") @PathVariable String sessionId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        PageResult<ChatPrivateMessageVO> result = privateMessageService.getMessagePage(sessionId, userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/message/{id}")
    @Operation(summary = "获取消息详情", description = "根据ID获取消息详细信息")
    public Result<ChatPrivateMessageVO> getMessageById(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        ChatPrivateMessageVO message = privateMessageService.getMessageById(id, userId);
        return Result.success(message);
    }

    @PostMapping("/send")
    @Operation(summary = "发送私聊消息", description = "发送私聊消息")
    public Result<String> sendPrivateMessage(@Validated @RequestBody ChatPrivateMessageDTO messageDTO) {
        String userId = UserContext.getUserId();
        String messageId = privateMessageService.sendPrivateMessage(messageDTO, userId);
        return Result.success(messageId);
    }

    @PostMapping("/message/{id}/recall")
    @Operation(summary = "撤回消息", description = "撤回已发送的消息")
    public Result<Boolean> recallMessage(
            @Parameter(description = "消息ID") @PathVariable String id,
            @Parameter(description = "撤回原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.recallMessage(id, userId, reason);
        return Result.success(result);
    }

    @DeleteMapping("/message/{id}")
    @Operation(summary = "删除消息", description = "删除指定消息")
    public Result<Boolean> deleteMessage(
            @Parameter(description = "消息ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.deleteMessage(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/messages/batch")
    @Operation(summary = "批量删除消息", description = "批量删除多条消息")
    public Result<Boolean> deleteMessagesBatch(@RequestBody List<String> ids) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.deleteMessagesBatch(ids, userId);
        return Result.success(result);
    }

    @PostMapping("/session/{sessionId}/read")
    @Operation(summary = "标记已读", description = "标记会话消息为已读")
    public Result<Boolean> markMessagesAsRead(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.markMessagesAsRead(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/session/{sessionId}/search")
    @Operation(summary = "搜索消息", description = "在会话中搜索消息")
    public Result<List<ChatPrivateMessageVO>> searchMessages(
            @Parameter(description = "会话ID") @PathVariable String sessionId,
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "消息类型") @RequestParam(required = false) Integer messageType,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        List<ChatPrivateMessageVO> messages = privateMessageService.searchMessages(
            sessionId, keyword, messageType, startTime, endTime, limit);
        return Result.success(messages);
    }

    @GetMapping("/session/{sessionId}/unread-count")
    @Operation(summary = "未读数量", description = "获取会话未读消息数量")
    public Result<Integer> getUnreadMessageCount(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        String userId = UserContext.getUserId();
        Integer count = privateMessageService.getUnreadMessageCount(sessionId, userId);
        return Result.success(count);
    }

    @GetMapping("/session/{sessionId}/latest")
    @Operation(summary = "最新消息", description = "获取会话最新消息")
    public Result<ChatPrivateMessageVO> getLatestMessage(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        String userId = UserContext.getUserId();
        ChatPrivateMessageVO message = privateMessageService.getLatestMessage(sessionId, userId);
        return Result.success(message);
    }

    @PostMapping("/session/create")
    @Operation(summary = "创建会话", description = "创建或获取私聊会话")
    public Result<String> createOrGetSession(
            @Parameter(description = "好友ID") @RequestParam String friendId) {
        String userId = UserContext.getUserId();
        String sessionId = privateMessageService.createOrGetSession(userId, friendId);
        return Result.success(sessionId);
    }

    @GetMapping("/sessions")
    @Operation(summary = "会话列表", description = "获取用户的私聊会话列表")
    public Result<List<Object>> getUserSessions() {
        String userId = UserContext.getUserId();
        List<Object> sessions = privateMessageService.getUserSessions(userId);
        return Result.success(sessions);
    }

    @DeleteMapping("/session/{sessionId}")
    @Operation(summary = "删除会话", description = "删除私聊会话")
    public Result<Boolean> deleteSession(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.deleteSession(sessionId, userId);
        return Result.success(result);
    }

    @PostMapping("/session/{sessionId}/clear")
    @Operation(summary = "清空消息", description = "清空会话中的所有消息")
    public Result<Boolean> clearSessionMessages(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = privateMessageService.clearSessionMessages(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "消息统计", description = "获取私聊消息统计信息")
    public Result<Object> getMessageStatistics(
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
        Object statistics = privateMessageService.getMessageStatistics(userId, startTime, endTime);
        return Result.success(statistics);
    }

    @DeleteMapping("/clean")
    @Operation(summary = "清理过期消息", description = "清理指定天数前的消息")
    public Result<Integer> cleanExpiredMessages(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") Integer days) {
        Integer count = privateMessageService.cleanExpiredMessages(days);
        return Result.success(count);
    }
}
